package com.crois.barrier.common.utils;

import com.sun.management.OperatingSystemMXBean;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.lang.management.ManagementFactory;
import static com.crois.barrier.common.constants.Constants.STANDALONE_MODE_PROPERTY_NAME;

/**
 * @author Hou Ze Yu
 * @description
 * @date 2020/9/30
 */
public class SystemUtils {
    /**
     * Standalone mode or not
     */
    public static final boolean STANDALONE_MODE = Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME);

    public static final String STANDALONE_MODE_ALONE = "standalone";

    public static final String STANDALONE_MODE_CLUSTER = "cluster";
    /**
     * barrier local ip
     */
    public static final String LOCAL_IP = InetUtils.getSelfIp();
    /**
     * The key of barrier home.
     */
    public static final String BARRIER_HOME_KEY = "barrier.home";
    /**
     * The home of barrier.
     */
    public static final String BARRIER_HOME = getBarrierHome();

    private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();



    public static float getLoad() {
        return (float) operatingSystemMXBean.getSystemLoadAverage();
    }

    public static float getCPU() {
        return (float) operatingSystemMXBean.getSystemCpuLoad();
    }

    public static float getMem() {
        return (float) (1 - (double) operatingSystemMXBean.getFreePhysicalMemorySize() / (double) operatingSystemMXBean
                .getTotalPhysicalMemorySize());
    }

    private static String getBarrierHome() {
        String doorHome = System.getProperty(BARRIER_HOME_KEY);
        if (StringUtils.isBlank(doorHome)) {
            doorHome = System.getProperty("user.home") + File.separator + "barrier";
        }
        return doorHome;
    }
}
